package com.jtlrm.ckd.mvp.view.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.base.sdk.util.ImageUtil;
import com.hyphenate.chat.EMGroup;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.entity.GroupMemberEntity;
import com.jtlrm.ckd.mvp.model.dao.UserHelper;

import java.util.List;

public class GroupDetailAdapter extends ArrayAdapter<GroupMemberEntity> {

    private int res;
    private EMGroup group;
    private boolean isOwener = false;

    OnDeleteListener onDeleteListener;


    public GroupDetailAdapter(Context context, int textViewResourceId, List<GroupMemberEntity> objects, EMGroup group) {
        super(context, textViewResourceId, objects);
        res = textViewResourceId;
        this.group = group;
        if (group.getOwner().equals(UserHelper.getInstance(context).getUserInfo().getEasemobId() + "")) {
            isOwener = true;
        }
    }

    public void setOnDeleteListener(OnDeleteListener onDeleteListener) {
        this.onDeleteListener = onDeleteListener;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(res, null);
            holder.imageView = convertView.findViewById(R.id.iv_avatar);
            holder.textView = convertView.findViewById(R.id.tv_name);
            holder.badgeDeleteView = convertView.findViewById(R.id.new_delete);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.textView.setText(getItem(position).getName());
        ImageUtil.loadCircleAvatarImage(holder.imageView, getItem(position).getHeadPicture());
        if (isOwener && !getItem(position).getEasemobId().equals(group.getOwner())) {
            holder.badgeDeleteView.setVisibility(View.VISIBLE);
        } else {
            holder.badgeDeleteView.setVisibility(View.GONE);
        }
        holder.badgeDeleteView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onDeleteListener != null){
                    onDeleteListener.deleteMember(getItem(position).getId());
                }
            }
        });
        return convertView;
    }

    private class ViewHolder {
        ImageView imageView;
        TextView textView;
        ImageView badgeDeleteView;
    }

    public interface OnDeleteListener {
        void deleteMember(String userId);
    }
}
